#!/usr/bin/env python
import sys
sys.path.append("../python")
import edbcli

if __name__ == "__main__":

	edb = edbcli.Client(["127.0.0.1:11911"])
	
	edb.query("DELETE * FROM test_domain;")
	edb.query("DELETE * FROM edbsync;")

	# test deleting of empty domain:
	edb.query("DELETE * FROM test_domain;")


	# ORDER BY testing:
	c = 10
	
	for x in range(c):
		results = edb.query("INSERT INTO test_domain VALUES( x:$x );", [{"x":x}])

	# ORDER BY ascending:
	results = edb.query("SELECT * FROM test_domain ORDER BY x:ASC;")
	if len(results) != c:
		print("FAILURE")
	elif int(results[0]["x"]) != 0:
		print("FAILURE")
	elif int(results[c-1]["x"]) != c-1:
		print("FAILURE")
	else:
		print("OK")

	# ORDER BY descending:
	results = edb.query("SELECT * FROM test_domain ORDER BY x:DESC;")
	if len(results) != c:
		print("FAILURE")
	elif int(results[0]["x"]) != c-1:
		print("FAILURE")
	elif int(results[c-1]["x"]) != 0:
		print("FAILURE")
	else:
		print("OK")

	# clean up ORDER BY testing
	edb.query("DELETE * FROM test_domain;")

	# insert and delete test (on _name attribute):
		
	c = 1
	
	for x in range(c):
		results = edb.query("INSERT INTO test_domain VALUES( _name:$x, arg1:$y );", [{"x":x, "y":x*x}])

	results = edb.query("SELECT * FROM test_domain;", [])
	if len(results) != c:
		print("FAILURE : len(results) was %d, should've been %d" % ( len(results), c) )
		print(str(results))
		sys.exit(0)
	else:
		print("OK")
		
	for x in range(c):
		results = edb.query("DELETE * FROM test_domain WHERE _name = $x;", [{"x":x}])
		
	
	
	# insert test (on non-_name attribute):
		
	c = 1000
	
	for x in range(c):
		results = edb.query("INSERT INTO test_domain VALUES( x:$x );", [{"x":x}])

	results = edb.query("SELECT * FROM test_domain;", [])
	if len(results) != c:
		print("FAILURE")
	else:
		print("OK")
	
	# delete test (on non-_name attribute):
	
	for x in range(c):
		results = edb.query("DELETE * FROM test_domain WHERE x = $x;", [{"x":x}])

	# query empty set:
	
	results = edb.query("SELECT * FROM test_domain;", [])
	if len(results) > 0:
		print("FAILURE")
	else:
		print("OK")
	
	# insert heterogeneous data types:
	results = edb.query("INSERT INTO test_domain VALUES( x:$x, y:$y, z:$z );", [{"x":1234, "y":"test attribute value", "z":56789}])
	if len(results) != 1:
		print("FAILURE")
	else:
		print("OK")

	results = edb.query("SELECT z FROM test_domain WHERE y = $y;", [{"y":"test attribute value"}] )
	if len(results) != 1 or int(results[0]["z"]) != 56789:
		print("FAILURE")
	else:
		print("OK")
	